#include "client.h"
#include "network/tlpacket.h"
#include "main.h"
Client::Client(int socketDescriptor, QObject *parent)
    : QThread(parent), socketDescriptor(socketDescriptor)
{
}

void Client::run()
{
    _Socket = new QTcpSocket();
    if (!_Socket->setSocketDescriptor(socketDescriptor)) {
        emit error(_Socket->error());
        return;
    }
    handler = new Handlers::SessionHandler(_Socket);
    connect(handler,SIGNAL(SetPlayer(Player*)),this,SLOT(SetPlayer(Player*)));
    connect(handler,SIGNAL(SendData(QByteArray)),this,SLOT(SendData(QByteArray)));

    _log->LogIt(QString("Connection from %1:%2").arg(_Socket->peerAddress().toString()).arg(_Socket->peerPort()));

    bool waitdata=false;
    QByteArray wdata;

    while (_Socket->state() == QAbstractSocket::ConnectedState)
    {
         if (_Socket->waitForReadyRead(1000))    //Waiting data to be read
         {
               QByteArray data = _Socket->readAll();        //Read all data
               //QMutexLocker locker(&mutex);
               if(data.isEmpty())
                   continue;
               if(waitdata)
               {
                    wdata.append(data);
                    wdata.clear();
               }

               QByteArray cmddata;
               Packets::TLPacket::pheader head;
               QBuffer buff(&data);
               buff.open(QBuffer::ReadWrite);
               QDataStream idata(&buff);

               while(!idata.atEnd())
               {
                   idata >> head.cmd;
                   idata >> head.size;
                   if(head.size>idata.device()->bytesAvailable())
                   {
                        idata << head.cmd;
                        idata << head.size;
                        wdata.resize(idata.device()->bytesAvailable());
                        idata.readRawData((char*)(wdata.data()+3),idata.device()->bytesAvailable());
                   }else{
                       cmddata.resize((int)head.size);
                       idata.readRawData(cmddata.data(),head.size);
                       Packets::TLPacket pkt(head,cmddata);
                       handler->InPacket(&pkt);
                   }
               }
         }
    }
  _log->LogIt(QString("Disconnected from %1:%2").arg(_Socket->peerAddress().toString()).arg(_Socket->peerPort()));
}
void Client::SetPlayer(Player* player)
{
    handler->setPlayerID(player->getID());
    _player = player;
}
void Client::SendData(QByteArray data)
{
    Packets::TLPacket pk(data);
    QMutexLocker locker(&mutex);
    _Socket->write(data);

    #ifdef TL2_DEBUG_SEND
        _log->LogIt(pk.StDump(),Logg::ODEBUG);
    #endif

}
